<?php

namespace app\api\controller;

use app\common\model\ApplicationsModel;
use think\App;
use app\common\model\CompanyModel;
use app\common\model\EquipmentServiceOrdersModel;
use app\common\model\AccountModel;
use app\common\model\AccountRecordModel;
use app\common\model\EquipmentModel;
use app\common\model\EquipmentsModel;
use think\Db;

/**
 * 设备相关API
 */
class Equipment extends Base
{

    protected $companyModel;
    protected $equipmentServiceOrdersModel;
    protected $accountRecordModel;
    protected $equipmentModel;
    protected $accountModel;
    protected $equipmentsModel;
    protected $applicationsModel;

    // 初始化构造方法
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->companyModel = new CompanyModel();  // 企业模型
        $this->equipmentServiceOrdersModel = new EquipmentServiceOrdersModel();
        $this->accountRecordModel = new AccountRecordModel();
        $this->equipmentModel = new EquipmentModel();
        $this->accountModel = new AccountModel();
        $this->equipmentsModel = new EquipmentsModel();
        $this->applicationsModel = new ApplicationsModel(); // 账户表模型
    }

    //获取设备列表
    public function getLists()
    {
        $api_host = $this->applicationsModel->getApiHost($this->parm['app_sn']);
        $url = $api_host . $this->api_url['getEquipmentList'];
        $page = $this->parm['page'] ?? 1;
        $pageSize = $this->parm['pageSize'] ?? 10;

        $param['page'] = $page;
        $param['pageSize'] = $pageSize;
        $param['device_no'] = $this->parm['device_no'] ?? '';
        $result = false;
        if (empty($param['device_no'])) {
            $result = json_decode($this->redis->hget('cloud_boss_device_list:' . $this->parm['app_sn'], $page), true);
        }
        if (!$result) {
            $result = http_post($url, json_encode($param));
            if ($result && $result['code'] == 0) {
                $data = $result['data'];
                $eq_lists = $this->equipmentModel->getAll(['app_sn' => $this->parm['app_sn']], 'service_start_time,service_expire_time,equipment_id');
                if (!empty($eq_lists)) {
                    $eq_lists = is_object($eq_lists) ? $eq_lists->toArray() : $eq_lists;
                    foreach ($data as $k => $v) {
                        $eq_info = searchArray($eq_lists, 'equipment_id', $v['equipment_id']);
                        if (empty($eq_info)) {
                            file_put_contents('./eq_log.txt', $v['equipment_id'] . '-' . $v['device_no'] . PHP_EOL, FILE_APPEND);
                        }
                        if (!empty($eq_info)) {
                            $eq_info = $eq_info[0];
                            $data[$k]['service_time'] = date('Y-m-d', $eq_info['service_start_time']) . '至' . date('Y-m-d', $eq_info['service_expire_time']);
                            $data[$k]['address'] = $v['province'] . $v['city'] . $v['area'] . $v['address'];
                        }
                    }
                }
                $result['data'] = $data;
                $this->redis->hset('cloud_boss_device_list:' . $this->parm['app_sn'], $page, json_encode($result));
                $this->redis->expire('cloud_boss_device_list:' . $this->parm['app_sn'], 1800);
            }
        }
        returnJson($result['code'], $result['msg'], $result['data'], $result['count'], $result['info']);

    }

    /**
     * showdoc
     * @catalog API文档/设备模块
     * @title 扣取服务费
     * @description 单个设备新装服务费或者续费
     * @method POST
     * @url api/Equipment/serviceFeePay
     * @param int $company_id 企业ID
     * @param int $app_sn 应用编号
     * @param int $account_role 账户角色1总后台,2运营中心,3城市合伙人
     * @param int $account_sn 账户编号
     * @param int $equipment_id 设备ID
     * @param int $equipments_sn 产品编号
     * @param int $type
     * @param int $service_start_time 服务开始时间
     * @return
     * @remark
     * @number 0
     * @author lcx
     * @date 2019-01-28
     */
    public function serviceFeePay()
    {
        $check = $this->checkParam($this->parm);
        if ($check['code'] != 0) {
            returnJson($check['code'], $check['msg']);
        }
        $company_no = $this->parm['company_no'] ?? '';
        if (!empty($this->parm['company_id'])) {
            $company_no = $this->companyModel->getValue(['company_id' => $this->parm['company_id'], 'app_sn' => $this->parm['app_sn']], 'company_no');
        }
        //如果设备未到期,直接返回
        $equipment_info = $this->equipmentModel->getOne(['equipment_id' => $this->parm['equipment_id'], 'app_sn' => $this->parm['app_sn'], 'company_no' => $company_no], 'service_expire_time,equipment_id,service_start_time');
        if (!empty($equipment_info) && $equipment_info['service_expire_time'] > time()) {
            returnJson(1100, '设备未到期');
        }
        $type = !empty($equipment_info) ? 2 : 1;//类型 1新增 2续约

        $money = 0;//服务费金额
        $service_pay_role = 1;
        $account_sn = $company_no;

        $equipments = $this->equipmentsModel->getOne(['equipments_sn' => $this->parm['equipments_sn']], 'new_install_service_money,renew_service_money,service_pay_role');
        if (!empty($equipments)) {
            $service_pay_role = $equipments['service_pay_role'];
            $money = $type == 1 ? $equipments['new_install_service_money'] : $equipments['renew_service_money'];
        }
        if ($money <= 0) {
            returnJson(-1000, $this->parm['equipments_sn'] . '该设备不需要支付服务费');
        }
        if ($service_pay_role != 1) {
            $account_sn = $this->parm['account_sn']['account_' . $service_pay_role - 1] ?? '';//扣款账户
            if (empty($account_sn)) {
                returnJson(-1000, '请选择支付账户');
            }
        }
        //判断账户余额
        $where = [
            'app_sn' => $this->parm['app_sn'],
            'company_no' => $company_no,
            'account_role' => $service_pay_role,
            'account_sn' => $account_sn
        ];

        $account = $this->accountModel->getOne($where, 'id,current_money');

        if (empty($account) || $account['current_money'] < $money) {
            returnJson(-1000, "账户余额不足,账户ID:" . $account['id'] ?? '');
//            //新增设备服务订单
//            $order['order_sn'] = 'ES' . order_sn();
//            $order['equipment_id'] = $this->parm['equipment_id'];
//            $order['type'] = $type;
//            $order['money'] = $money;
//            $order['service_start_time'] = $this->parm['service_start_time'] ?? time();
//            $order['service_end_time'] = strtotime(date("Y-m-d 23:59:59", strtotime("+1 years", $order['service_start_time'])));
//            $order['service_cycle'] = 1;
//            $order['status'] = 2;
//            $order['create_time'] = time();
//            $order['account_id'] = $account['id'] ?? 0;
//            $order['remarks'] = '账户余额不足,扣费失败';
//            $this->equipmentServiceOrdersModel->add($order);
//            returnJson(-1000, "账户余额不足,账户ID:" . $account['id'] ?? '');
        }
        Db::startTrans();
        try {
            //新增设备信息
            if (empty($equipment_info)) {
                $equipment_data['equipment_id'] = $this->parm['equipment_id'];
                $equipment_data['app_sn'] = $this->parm['app_sn'];
                $equipment_data['company_no'] = $company_no;
                $equipment_data['service_start_time'] = $this->parm['service_start_time'] ?? time();
                $equipment_data['service_expire_time'] = strtotime(date("Y-m-d 23:59:59", strtotime("+1 years", $equipment_data['service_start_time'])));
                $equipment_data['last_pay_service_time'] = time();
                $equipment_data['create_time'] = time();
                $this->equipmentModel->add($equipment_data);
                $service_start_time = $equipment_data['service_start_time'];
            } else {
                $service_start_time = $this->parm['service_start_time'] ?? $equipment_info['service_start_time'];
            }
            //新增设备服务订单
            $order['order_sn'] = 'ES' . order_sn();
            $order['equipment_id'] = $this->parm['equipment_id'];
            $order['type'] = $type;
            $order['money'] = $money;
            $order['service_start_time'] = $service_start_time;
            $order['service_end_time'] = strtotime(date("Y-m-d 23:59:59", strtotime("+1 years", $service_start_time)));
            $order['service_cycle'] = 1;
            $order['status'] = 1;
            $order['create_time'] = time();
            $order['account_id'] = $account['id'];
            $order_id = $this->equipmentServiceOrdersModel->add($order);
            //减少账户金额
            $current_money = $account['current_money'] - $money;
            $this->accountModel->edit(['id' => $account['id']], ['current_money' => $current_money]);
            //新增账户记录
            $record['account_id'] = $account['id'];
            $record['money'] = $money;
            $record['type'] = 2;
            $record['source'] = $type == 1 ? 3 : 4;
            $record['order_id'] = $order_id;
            $record['create_time'] = time();
            $this->accountRecordModel->add($record);
            // 事务提交
            Db::commit();
            returnJson(0, "扣费成功");
        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            returnJson(-1000, "扣费失败" . $e->getMessage());
        }
    }

    public function checkParam($parm)
    {
        if (empty($parm['company_id'] ?? '') && empty($parm['company_no'] ?? '')) {
            return returnResult(-1001, "缺少参数company_id或者company_no");
        }
        if (empty($parm['app_sn'] ?? '')) {
            return returnResult(-1001, "缺少参数app_sn");
        }
        if (empty($parm['equipment_id'] ?? '')) {
            return returnResult(-1001, "缺少参数equipment_id");
        }
        if (empty($parm['equipments_sn'] ?? '')) {
            return returnResult(-1001, "缺少参数equipments_sn");
        }

        return returnResult(0, "OK");
    }


}
